package com.yimils.core.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yimils.core.sys.entity.RoleResourceEntity;
import com.yimils.core.sys.mapper.RoleResourceMapper;
import com.yimils.core.sys.po.RoleResourceDo;
import com.yimils.core.sys.utils.IdCheckUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service("roleResourceService")
public class RoleResourceServiceImpl extends ServiceImpl<RoleResourceMapper, RoleResourceEntity> implements RoleResourceService {
    @Autowired(required = false)
    private RoleResourceMapper roleResourceMapper;

    @Override
    public List<RoleResourceEntity> getRoleResources(Long roleId) {
        List<RoleResourceEntity> res = null;
        if (IdCheckUtils.isAdmin(roleId)) {
            throw new AuthorizationException();
        } else {
            QueryWrapper<RoleResourceEntity> qw = new QueryWrapper<>();
            qw.eq("roleId", roleId);
            res = list(qw);
        }
        return res;
    }

    @Transactional
    @Override
    public boolean updateRoleResourceForBatch(Long roleId, List<RoleResourceEntity> entityList) {
        roleResourceMapper.cleanActiveForRole(roleId);
        if (!CollectionUtils.isEmpty(entityList)) {
            return saveOrUpdateBatch(entityList);
        }
        return true;
    }

    public List<RoleResourceEntity> getRoleResourcesTree(Long roleId) {
        List<RoleResourceEntity> model = new ArrayList<>();
        List<RoleResourceDo> midParents = roleResourceMapper.getRoleResourceMidParent(roleId);
        for (RoleResourceDo roleResourceDo : midParents) {
            List<RoleResourceDo> endPoints = roleResourceMapper.getRoleResourceEndpoint(roleId, roleResourceDo.getName());
            if (endPoints.size() >= 3 || endPoints.size() == 0) {
                //如果增删改三个节点都有权限或者都没有权限，只返回view节点，前端会自动勾选上其余3个节点
                model.add(getById(roleResourceDo.getId()));
            } else {
                //对应只有部分增删改权限的情况，只返回部分节点
                for (RoleResourceDo endPoint : endPoints) {
                    model.add(getById(endPoint.getId()));
                }
            }
        }

        return model;
    }
}
